package com.cmcc.passenger.data

import com.cmcc.passenger.R
import com.cmcc.passenger.config.AppConfig
import com.cmcc.shared.config.SpKeys
import com.cmcc.passenger.data.service.AppApiService
import com.cmcc.passenger.data.service.GoogleApiService
import com.cmcc.shared.BaseApplication
import com.cmcc.shared.SdkManager
import com.cmcc.shared.config.SharedConfig
import com.cmcc.shared.network.RetrofitRequest
import com.cmcc.shared.network.interceptor.HttpLoggingInterceptor
import com.cmcc.shared.utils.SpHelper
import com.cmcc.shared.utils.TokenUtils
import com.jakewharton.retrofit2.adapter.kotlin.coroutines.CoroutineCallAdapterFactory
import okhttp3.Interceptor

class Network private constructor() {

    var googleApiService = RetrofitRequest.Builder().baseUrl(AppConfig.GOOGLE_API_URL)
        .setLogLevel(HttpLoggingInterceptor.Level.BODY)
        .addIntercptor(Interceptor { chain ->
            val newUrl = chain.request().url()
                .newBuilder()
                .addQueryParameter(
                    "key",
                    SdkManager.getApplicationContext()!!.getString(R.string.google_maps_key)
                )
                .build()

            val newRequest = chain.request()
                .newBuilder()
                .url(newUrl)
                .build()
            chain.proceed(newRequest)
        })
        .addCallAdapterFactory(CoroutineCallAdapterFactory())
//        .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
        .build()
        .createService(GoogleApiService::class.java)

    var appApiService = RetrofitRequest.Builder().baseUrl(AppConfig.APP_DOMAIN)
        .setLogLevel(HttpLoggingInterceptor.Level.BODY)
        .addHeader("Content-Type","application/json")
        .addHeader("Accept-Language", when (SdkManager.getLanguage()) {
            0 -> "en-US"
            1 -> "zh-CN"
            2 -> "zh-HK"
            else -> "zh-HK"
        })
        .addHeader(
            "Authorization",
//            "Bearer "+SpHelper.getParam(SdkManager.getApplicationContext()!!, SpKeys.USER_TOKEN,""))
            "Bearer "+ TokenUtils.getUserToken()
        )
        .addCallAdapterFactory(CoroutineCallAdapterFactory())
//        .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
        .build()
        .createService(AppApiService::class.java)

    companion object {
        @Volatile
        private var instance: Network? = null

        fun getInstance(): Network {
            return instance ?: synchronized(this) {
                instance ?: Network().also { instance = it }
            }
        }
    }

}
